package com.bd.scm.module.exception;

import com.bd.scm.module.utils.ResultUtil;
import com.bd.utils.exception.BdExceptionHandler;
import com.bd.utils.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yufc
 */
@RestControllerAdvice
@Slf4j
public class ScmExceptionHandler extends BdExceptionHandler {

    @ExceptionHandler(ScmException.class)
    public Result<?> handleException(ScmException e, HttpServletRequest request){
        log.error("ScmException-------------------" + getLogMsg(e.getCode(), e.getMessage(), request), e);
        return ResultUtil.error(e.getCode(), e.getMessage());
    }

    @Override
    @ExceptionHandler({Exception.class})
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        log.error("Exception-------------------" + e.getMessage(), e);
        return Result.error("系统错误，请联系管理员.");
    }

    public Map<String,Object> getLogMsg(int code, String msg, HttpServletRequest request){
        Map<String,Object> map=new HashMap<>();
        map.put("code", code);
        map.put("msg", msg);
        map.put("requestUrl",request.getRequestURL());

        return map;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<?> handlerNoFoundException(Exception e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        return ResultUtil.error(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> HttpRequestMethodNotSupportedException(Exception e, HttpServletRequest request){
        log.error(e.getMessage(), e);
        return ResultUtil.error("没有权限，请联系管理员授权");
    }

}
